/*
 * @(#)NextTag.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.web.taglibs.pager;

import java.text.MessageFormat;

import javax.servlet.jsp.JspWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nhncorp.usf.core.config.PagerConfigInfo;
import com.nhncorp.usf.core.config.PagerConfigInfos;
import com.nhncorp.usf.core.result.template.directive.PagerInfo;

/**
 * 다음 페이지로 이동하기 위한 {@link PagerTag}.
 *
 * @author Web Platform Development Team
 */
public class NextTag extends PagerTag {
	static final long serialVersionUID = 2472446301957067537L;

	static Log log = LogFactory.getLog(NextTag.class);

	public NextTag() {
	}

	public NextTag(String... appendings) {
		super(appendings);
	}

	/**
	 * @param parent {@link NavigatorTag}
	 * @param pagerInfo {@link PagerInfo}
	 * @throws Exception Exception
	 * */
	protected void generate(NavigatorTag parent, PagerInfo pagerInfo) throws Exception {
		PagerConfigInfo pagerConfig = PagerConfigInfos.get(parent.pagerType);
		
		if (pagerConfig == null) {
			throw new IllegalArgumentException("failed to find pager config for type '" + parent.pagerType + "'");
		}
		
		JspWriter out = pageContext.getOut();

		if (parent.nextPage > parent.lastPage) {
			String nextOff = pagerConfig.getNextOff();
			out.print(resolve(nextOff, pagerConfig.getDataHandlerName()));
		} else {
			String queryString = getQueryString(pagerInfo);
			String startTag = getStartTag(parent, queryString, parent.nextPage, pagerConfig.getNextAtagAttribute());
			String endTag = END_ATAG;

			String next = pagerConfig.getNext();
			String preMessage = resolve(next, pagerConfig.getDataHandlerName());
			out.println(MessageFormat.format(preMessage, startTag, endTag, parent.nextPage));
		}
	}

	/**
	 * {@inheritDoc}
	 * */
	protected void failed(Exception ex) {
		log.error(ex);
	}
}